import gps
import xmlrpclib

import getopt
import csv
import time
import threading
import shutil
import sys
import os

#cond = threading.Condition()

def usage():
    print "whereiam.py 0.01. Available options:"
    print "         -h      Display this help"
    print "         -d      Turn on debugging"
    print "         -l      Turn on logging mode"
    print "         -h      Hostname/IP of GPSd (Default: localhost)"
    print "         -p      Port of GPSd (Default: 2947)"
    print "         -w      WebService address to send data (Default: none)"
    print "         -i      Interval to pool GPSd (Default: 5 seconds)"
    print "         -i      Interval to send to webservice (Default: 1 second)"
    sys.exit(0)

class DataLogger(threading.Thread):
    def __init__ (self,  host = '127.0.0.1', port = '2947', debug = 0, interval = 5):
        self.host = host
        self.port = port
        self.debug = debug
        self.interval = interval
        self.gpsd = gps
        threading.Thread.__init__ ( self )

    def run(self):
        self.connect()

        while 1:
            try:
                self.query()
            except:
                self.connect()

            if not (self.gpsd.fix.latitude==0 and self.gpsd.fix.longitude==0):
                self.writeToFile()

            time.sleep(self.interval)

    def connect(self):
        try:
            self.gpsd = gps.gps(self.host,self.port)
        except:
            print 'Error trying to connect in host=',self.host,' and port=',self.port
            time.sleep(self.interval)

    def query(self):
        try:
            self.gpsd.query('admosy')
            # a = altitude, d = date/time, m=mode,
            # o=postion/fix, s=status, y=satellites
        except:
            print 'Error aquiring data from gpsd, retrying to connect in ',self.interval,' seconds.'
            time.sleep(self.interval)

    def writeToFile(self):
        #cond.acquire()
        try:
            file = open('whereiam.csv', 'a')
            writer = csv.writer(file)
        except:
            print 'Error writing whereiam.csv file'
        writer.writerow([self.gpsd.fix.time, self.gpsd.fix.latitude, self.gpsd.fix.longitude, self.gpsd.fix.track, self.gpsd.fix.speed, self.gpsd.fix.climb, self.gpsd.fix.altitude])
        file.close
        #cond.notifyAll()
        #cond.release()


class WebServiceSender(threading.Thread):
    def __init__ (self,  webservice, debug = 0, interval = 1):
        self.webservice=webservice
        self.debug=debug
        self.interval=interval
        self.timestamp=''
        self.latitude=''
        self.longitude=''
        self.track=''
        self.speed=''
        self.climb=''
        self.altitude=''
        threading.Thread.__init__ ( self )

    def run(self):
        self.readFromFile()

    def send(self):
        try:
            server = xmlrpclib.Server(self.webservice)
        except:
            print "WebService Timed Out"
            raise WebService, "Connection Timed Out"
            return 1
        try:
            print server.maps.receiveCoords(self.timestamp, self.latitude, self.longitude, self.track, self.speed, self.climb, self.altitude)
        except:
            print "Error sending data to webservice"
            raise WebService, "Error sending data"
            return 1

    def readFromFile(self):
        while 1:
            time.sleep(self.interval)
            if (not os.path.exists('whereiam.csv')):
                continue
            #cond.acquire()
            try:
                file = open('whereiam.csv', 'r')
            except:
                print 'Error reading from whereiam.csv file'
                #cond.notifyAll()
                #cond.release()
                continue
            line = file.readline()
            if not line=="":
                timestamp,latitude,longitude,track,speed,climb,altitude = line.split(',')
                self.timestamp = timestamp
                self.latitude = latitude
                self.longitude = longitude
                self.track = track
                self.speed = speed
                self.climb = climb
                self.altitude = altitude
            else:
                #cond.notifyAll()
                #cond.release()
                continue
            try:
                self.send()
            except:
                file.close()
                #cond.notifyAll()
                #cond.release()
                continue
            finally:
                file.close()
                #cond.notifyAll()
                #cond.release()

            #cond.acquire()
            try:
                shutil.move('whereiam.csv','temp.csv')
            finally:
                f = open("temp.csv","r")
                ignore = f.readline()
                if not ignore=="":
                    tmpFile = f.read()
                    file = open("whereiam.csv", "w+")
                    file.write(tmpFile)
                    file.close()
                f.close()
            #cond.notifyAll()
            #cond.release()

DataLogger(host='ibiza',port='2947').start()
webserviceURL="http://www.wsartori.com/gps/ws_whereiam.php"
WebServiceSender(webservice=webserviceURL).start()